package httphandle

import (
	"emb/emb_server/util/dbutil"
	"emb/emb_server/util/handleutil"
	"fmt"
	"net/http"
	"strconv"
)

// s account  string,password string
// r Message string,
//   {icon string,nickname string,isManager bool}

type userMsg struct {
	NickName  string
	Icon      string
	IsManager bool
}

func login(w http.ResponseWriter, r *http.Request) {

	var httpCode = http.StatusOK
	var info = "success"
	var information interface{}

	fmt.Println("请求方IP地址：", r.RemoteAddr)
	defer func() {
		handleutil.SendMsg(w, httpCode, info, information)
	}()

	setHeader(w)

	err := r.ParseForm()
	if err != nil {
		httpCode = http.StatusBadRequest
		info = "参数解析失败！请使用x-www-form-urlencoded格式传输参数数据！"
		fmt.Println("An err from login.PaseForm:---", err.Error())
		return
	}

	id := r.Form["account"]
	password := r.Form["password"]

	// fmt.Println("login:id=", id[0])
	// fmt.Println("login:password=", password)
	// fmt.Println("login: idType:", reflect.TypeOf(id[0]))

	if len(id) != 1 || id == nil {
		info = "id 输入有误"
		httpCode = http.StatusBadRequest
		fmt.Println("An err from login:--- id != 1|| id == nil")
		return
	}
	if len(password) != 1 || password == nil {
		info = "password 输入有误"
		httpCode = http.StatusBadRequest
		fmt.Println("An err from login:--- password != 1|| password == nil")

		return
	}
	_, err = strconv.ParseUint(id[0], 10, 64)
	if err != nil {
		info = "账号格式有误"
		httpCode = http.StatusBadRequest
		fmt.Println("An err from login.ParseUint:---", err.Error())

		return
	}

	info, information, ok := checkOut(id[0], password[0])
	if !ok {
		httpCode = http.StatusBadRequest
		return
	}
	// fmt.Println("login:informath=", information)

}

//检测用户密码是否正确
func checkOut(id string, pwd string) (string, interface{}, bool) {

	var info = "success"
	var userInfo userMsg
	var nickName, icon string
	var isManager bool

	sql := "select nickname,icon,users.ismanager from users,objects where users.id = $1 and password = $2 and objects.id = $3"
	dbutil.InitDb()
	db := dbutil.GetDb()
	defer dbutil.CloseDb(db)

	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		info = "An error from login.checkOut.stmt:---" + err.Error()
		fmt.Println("An error from login.checkOut.stmt:---", err.Error())
		return info, nil, false
	}

	rows, err := stmt.Query(id, pwd, id)
	defer rows.Close()

	if !rows.Next() {
		info = "账号密码有误"
		return info, nil, false
	} else {
		err = rows.Scan(&nickName, &icon, &isManager)
		if err != nil {
			info = "An error from login.checkOut.Scan:---" + err.Error()
			fmt.Println("An error from login.checkOut.Scan:---", err.Error())
			return info, nil, false
		}
	}
	userInfo.NickName = nickName
	userInfo.Icon = icon
	userInfo.IsManager = isManager

	return info, userInfo, true
}
